// @flow
import React from 'react'
import styles from './KmxPage.css'
import { Button, Select, Row, Col, Input, Icon, Form, Tooltip } from 'antd'
import NoticeMessage from '../NoticeMessage'
import R from 'ramda'
const Option = Select.Option
const FormItem = Form.Item
type Props = {
  nextStep: Function,
  preStep: Function,
  step: string,
  form: Object,
  cmData: Object,
  getKmxName: Function
}
type State ={
  versions: Array<Object>,
  value: string,
  lists: Array<Object>,
  url: string,
  type: string,
  disabled: boolean,
  imgStatus: boolean,
  loading: boolean,
  kmxName: string,
  visible: string
}
class KmxPage extends React.Component {
  props: Props
  state: State
  stepClick: () => void
  refreshPackage: () => void
  getVersions: () => void
  selectChange: () => void
  urlChange: () => void
  typeChange: () => void
  handleSubmit: () => void
  createKmx: () => void
  getKmxMess: () => void
  deleteKmx: () => void
  installDocker: () => void
  constructor (props: Props) {
    super(props)
    this.state = {
      versions: [],
      value: '',
      lists:[],
      url: '',
      type: 'http://',
      disabled: true,
      imgStatus: false,
      loading: false,
      kmxName: '',
      visible: 'hidden'
    }
    this.stepClick = this.stepClick.bind(this)
    this.refreshPackage = this.refreshPackage.bind(this)
    this.getVersions = this.getVersions.bind(this)
    this.selectChange = this.selectChange.bind(this)
    this.urlChange = this.urlChange.bind(this)
    this.typeChange = this.typeChange.bind(this)
    this.handleSubmit = this.handleSubmit.bind(this)
    this.createKmx = this.createKmx.bind(this)
    this.getKmxMess = this.getKmxMess.bind(this)
    this.deleteKmx = this.deleteKmx.bind(this)
    this.installDocker = this.installDocker.bind(this)
  }

  componentDidMount () {
    console.info('KMXPAGE: ', this.props)
  }

  componentWillReceiveProps (nextProps: Object) {
    if (!R.equals(nextProps.step, this.props.step) && nextProps.step === 2) {
      this.getVersions()
    }
  }

  stepClick (val: string) {
    if (val === 'pre') {
      this.props.preStep(1)
    }
    if (val === 'next') {
      this.handleSubmit('checked')
      // this.props.nextStep(3)
    }
  }

  handleSubmit (method) {
    this.props.form.validateFields((err, values) => {
      console.log('Received values of form: ', values)
      let submitData = {}
      const fetchPake = () => {
        submitData.type = values.installselect
        submitData.url = values.installpackage
        submitData.value = values.version
        console.info(JSON.stringify(submitData, null, 4))
        this.fetchPackageData(submitData)
      }
      if (err && !err.hasOwnProperty('installpackage') && method === 'getPackageImg') {
        fetchPake()
      }
      if (!err) {
        if (method === 'getPackageImg') {
          fetchPake()
        }

        if (method === 'checked') {
          submitData.cmAPI = this.props.cmData
          submitData.packagesUrl = `${values.installselect === 'http://' ? 'http://' : ''}${values.installpackage}`
          submitData.dockerRegistry = values.dockerRegistry
          submitData.version = values.version
          submitData.sshPort = parseInt(values.sshPort)
          console.info(JSON.stringify(submitData, null, 4))
          this.createKmx(submitData)
        }
      }
    })
  }

  refreshPackage () {
    this.handleSubmit('getPackageImg')
  }

  fetchPackageData (data) {
    const { value, url, type } = data
    const xurl = `${__CM_URL__}kmx/versions?version=${value}&url=${`${type === 'local' ? '' : type}${url}`}`
    fetch(xurl)
    .then((response) => {
      if (!(response.status >= 200 && response.status < 300) || response.status === 304) {
        console.error(response.status)
      }
      return response.json()
    })
    .then((json) => {
      console.info(json)
      if (json.code === 1) {
        throw new Error(json.message, 'KmxPage.js')
      }
      const data = Object.keys(json.body).map((li) => {
        return { name: li, status: json.body[li] }
      })
      this.setState({
        lists: data,
        disabled: data.map(x => x.status).includes(false),
        imgStatus: !data.map(x => x.status).includes(false)
      })
    })
    .catch((err) => {
      console.error(err)
      new NoticeMessage().createNotice({
        type: 'error',
        title: '错误提示',
        message: (err && err.message) ? err.message : err })
    })
  }

  getVersions () {
    const url = `${__CM_URL__}kmx/versions`
    fetch(url)
    .then((response) => {
      if (!(response.status >= 200 && response.status < 300) || response.status === 304) {
        console.error(response.status)
      }
      return response.json()
    })
    .then((json) => {
      if (json.code === 1) {
        throw new Error(json.message, 'KmxPage.js')
      }
      console.info(json.body.items.map(x => x.version)[0])
      this.setState({
        versions: json.body.items.map(x => x.version),
        value: json.body.items.map(x => x.version)[0]
      })
    })
    .catch((err) => {
      console.error(err)
    })
  }
// 创建KMX
  createKmx (data) {
    this.setState({ loading: true })
    const url = `${__CM_URL__}kmxes`
    fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
    })
    .then((response) => {
      if (!(response.status >= 200 && response.status < 300) || response.status === 304) {
        console.error(response.status)
      }
      return response.json()
    })
    .then((json) => {
      if (json.code === 1) {
        throw new Error(json.message, 'KmxPage.js')
      }
      console.info(json)
      this.props.getKmxName(json.body.name)
      this.installDocker(json.body.name)
    })
    .catch((err) => {
      console.error(err)
      this.setState({ loading: false, visible: 'visible' })
      this.getKmxMess(data.cmAPI.ipAddress)
      new NoticeMessage().createNotice({
        type: 'error',
        title: '错误提示',
        message: (err && err.message) ? err.message : err })
    })
  }

  // 安裝docker服務
  installDocker (name) {
    const url = `${__CM_URL__}kmxes/${name}/installDocker`
    fetch(url, {
      method: 'POST'
    })
    .then((response) => {
      if (!(response.status >= 200 && response.status < 300) || response.status === 304) {
        console.error(response.status)
      }
      return response.json()
    })
    .then((json) => {
      if (json.code === 1) {
        throw new Error(json.message, 'KmxPage.js')
      }
      this.setState({ loading: false })
      this.props.nextStep(3)
    })
    .catch((err) => {
      console.error(err)
      this.setState({ loading: false })
      new NoticeMessage().createNotice({
        type: 'error',
        title: '错误提示',
        message: (err && err.message) ? err.message : err })
    })
  }
// 获取已经存在的KMX
  getKmxMess (ip) {
    const url = `${__CM_URL__}kmxes?cmIp=${ip}`
    fetch(url)
    .then((response) => {
      if (!(response.status >= 200 && response.status < 300) || response.status === 304) {
        console.error(response.status)
      }
      return response.json()
    })
    .then((json) => {
      if (json.code === 1) {
        throw new Error(json.message, 'KmxPage.js')
      }
      this.setState({
        kmxName: json.body.name
      })
    })
    .catch((err) => {
      console.error(err)
      this.setState({ visible: 'hidden' })
      new NoticeMessage().createNotice({
        type: 'error',
        title: '错误提示',
        message: (err && err.message) ? err.message : err })
    })
  }
  // 已经配置过的KMX服务，需要进行删除
  deleteKmx () {
    const url = `${__CM_URL__}kmxes/${this.state.kmxName}?force=true`
    fetch(url, {
      method: 'DELETE'
    })
    .then((response) => {
      if (!(response.status >= 200 && response.status < 300) || response.status === 304) {
        console.error(response.status)
      }
      return response.json()
    })
    .then((json) => {
      if (json.code === 1) {
        throw new Error(json.message, 'KmxPage.js')
      }
      new NoticeMessage().createMessage({
        type: 'success',
        message: '删除成功！' })
      this.setState({ visible: 'hidden' })
    })
    .catch((err) => {
      console.error(err)
      new NoticeMessage().createNotice({
        type: 'error',
        title: '错误提示',
        message: (err && err.message) ? err.message : err })
    })
  }

  selectChange (val: string) {
    console.info(val)
    this.setState({ value: val })
  }

  urlChange (e: Object) {
    // console.info(e.target.value)
    this.setState({ url: e.target.value })
  }

  typeChange (val: string) {
    this.setState({ type: val })
  }

  ipCheck (rule, value, callback) {
    const reg = /((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d))))/
    if (value && !reg.test(value)) {
      callback(new Error('请输入正确的安装包地址'))
    } else {
      callback()
    }
  }
  render () {
    const { versions, lists, disabled, kmxName, visible } = this.state
    const { getFieldDecorator } = this.props.form
    return (
      <div className={styles['content']}>
        <div className={styles['main']}>
          <Form>
            <div className={styles['item']}>
              <header>
                KMX依赖：
              </header>
              <article>
                <Row gutter={10}>
                  <Col span={3}>
                    <span className={styles['label']}>
                      安装包&nbsp;
                      <Tooltip title='eg:192.168.130.52/cs'>
                        <Icon type='question-circle-o' />
                      </Tooltip>:
                    </span>
                  </Col>
                  <Col span={4}>
                    <FormItem style={{ height: '40px', paddingBottom: '0' }}>
                      {getFieldDecorator('installselect', {
                        initialValue: 'http://'
                      })(
                        <Select style={{ width: '100%' }}
                          key='installpackage' onChange={this.typeChange}>
                          <Option value='http://'>http://</Option>
                          <Option value='local'>本地</Option>
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                  <Col span={17}>
                    <FormItem>
                      {getFieldDecorator('installpackage', {
                        rules: [{ required: true, message: '请输入安装包路径！' }, {
                          validator: this.ipCheck
                        }]
                      })(
                        <Input suffix={<Icon type='sync' onClick={this.refreshPackage} />} onChange={this.urlChange} />
                      )}
                    </FormItem>
                  </Col>
                </Row>
                <Row gutter={10}>
                  <Col span={3} style={{ textAlign: 'right' }}><span className={styles['label']}>版&emsp;本:</span></Col>
                  <Col span={4}>
                    {getFieldDecorator('version', {
                      initialValue: versions[0]
                    })(
                      <Select style={{ width: '100%' }} key='model' onSelect={this.selectChange}>
                        {
                          versions.map((op) => {
                            return <Option value={op} key={op}>{op}</Option>
                          })
                        }
                      </Select>
                    )}
                  </Col>
                  <Col span={17}>
                    <div className={styles['list']}>
                      <ul>
                        {
                          lists.map((item) => {
                            return <li key={item.name} data-info={item.status ? 'success' : 'error'}>{item.name}</li>
                          })
                        }
                      </ul>
                    </div>
                  </Col>
                </Row>
              </article>
            </div>
            <div className={styles['item']}>
              <header>私有仓库:</header>
              <article>
                <Row gutter={10} style={{ paddingBottom: '20px' }}>
                  <Col span={5}>
                    <span className={styles['label']}>
                      私有仓库URL
                      &nbsp;
                      <Tooltip title='eg:kmx.k2data.com.cn:5000'>
                        <Icon type='question-circle-o' />
                      </Tooltip>:
                    </span>
                  </Col>
                  <Col span={19}>
                    <FormItem>
                      {getFieldDecorator('dockerRegistry', {
                        rules: [{ required: true, message: '请输入私有仓库URL!' }],
                        initialValue: 'kmx.k2data.com.cn:5000'
                      })(
                        <Input />
                      )}
                    </FormItem>
                  </Col>
                </Row>
                <Row gutter={10} style={{ paddingBottom: '20px' }}>
                  <Col span={5} style={{ textAlign: 'right' }}>
                    <span className={styles['label']}>
                      SSH端口&nbsp;
                      <Tooltip title='eg:6000'>
                        <Icon type='question-circle-o' />
                      </Tooltip>:
                    </span>
                  </Col>
                  <Col span={19}>
                    <FormItem>
                      {getFieldDecorator('sshPort', {
                        rules: [{ required: true, message: '请输入SSH端口' }],
                        initialValue: 60000
                      })(
                        <Input />
                      )}
                    </FormItem>
                  </Col>
                </Row>
              </article>
            </div>
          </Form>
        </div>
        <div className={styles['btn']}>
          <div style={{ float: 'right' }}>
            <Button type='danger' onClick={this.deleteKmx} style={{ visibility: visible }}>
              删除{kmxName}
            </Button>&emsp;
            <Button onClick={() => { this.stepClick('pre') }}>上一步</Button> &emsp;
            <Button onClick={() => { this.stepClick('next') }} type='primary' disabled={disabled}>下一步</Button>
          </div>
        </div>
      </div>
    )
  }
}

export default Form.create()(KmxPage)
